package com.arrays;

public class BinarySearch0123_704 {
    public int search(int[] nums, int target) {
//        int res = -1;
//        for (int i = 0; i < nums.length; i++) {
//            for (int j = nums.length-1; j >=i; j--) {
//                int mid = (j-i)/2 + i;
//                if(nums[mid] == target) return mid;
//                if(nums[mid] > target) j = mid-1;
//                if(nums[mid] < target) i = mid+1;
//            }
//        }
//        return res;

        //避免循环超时
        if(target > nums[nums.length-1] || target < nums[0]) return -1;
        int left = 0, right = nums.length-1;
        while (left<=right){
            int mid = (right+left) >> 2;
            if(nums[mid] == target) return mid;
            if(nums[mid] > target) right = mid-1;
            if(nums[mid] < target) left = mid+1;
        }
        return -1;
    }

}
